<- readLines("sample.txt") sample
Part 1
Input
<- readLines("input.txt")
input
head(input, 10)
[1] "U 2" "D 2" "R 2" "U 2" "D 1" "L 2" "R 2" "D 1" "R 2" "D 1"
Part 1
Code
<- function(head_coord, knot_coord) {
move_knot
# if the head and tail aren't touching and aren't in the same row or column
if (abs(head_coord$x - knot_coord$x) > 1 | abs(head_coord$y - knot_coord$y) > 1) {
<- list(
available_coord list(x = knot_coord$x + 1, y = knot_coord$y),
list(x = knot_coord$x + 1, y = knot_coord$y + 1),
list(x = knot_coord$x + 1, y = knot_coord$y - 1),
list(x = knot_coord$x - 1, y = knot_coord$y),
list(x = knot_coord$x - 1, y = knot_coord$y + 1),
list(x = knot_coord$x - 1, y = knot_coord$y - 1),
list(x = knot_coord$x, y = knot_coord$y + 1),
list(x = knot_coord$x, y = knot_coord$y - 1),
list(x = knot_coord$x, y = knot_coord$y)
)
# Coordinate difference are computed between head and all possible future
# knot position
<- unlist(
coord_diff ::map(available_coord,
purrr~ abs(.x$x - head_coord$x) + abs(.x$y - head_coord$y)))
# new knot coordinate is the one with lowest difference
<- available_coord[[which(coord_diff == min(coord_diff))]]
knot_coord
}return(knot_coord)
}
<- list(x=0,y=0)
head_coord <- list(x=0,y=0)
tail_coord
<- c()
visited_coord
for (move in input) {
<- unlist(strsplit(move, " "))
move_vec
<- move_vec[1]
direction <- move_vec[2]
distance
for (d in 1:distance) {
# message(d)
if (direction == "R") {
$x <- head_coord$x + 1
head_coordelse if (direction == "L"){
} $x = head_coord$x - 1
head_coordelse if (direction == "U") {
} $y = head_coord$y + 1
head_coordelse if (direction == "D") {
} $y = head_coord$y - 1
head_coord
}
<- move_knot(head_coord = head_coord, knot_coord = tail_coord)
tail_coord
<- c(visited_coord, paste(tail_coord$x, tail_coord$y, sep = ";"))
visited_coord
} }
Result
length(unique(visited_coord))
[1] 6337
Part 2
<- list()
knots
for (i in 1:10) {
<- list(x=0, y=0)
knots[[i]]
}
<- c()
visited_coord
for (move in input) {
<- unlist(strsplit(move, " "))
move_vec
<- move_vec[1]
direction <- move_vec[2]
distance
for (d in 1:distance) {
if (direction == "R") {
1]]$x <- knots[[1]]$x + 1
knots[[else if (direction == "L"){
} 1]]$x = knots[[1]]$x - 1
knots[[else if (direction == "U") {
} 1]]$y = knots[[1]]$y + 1
knots[[else if (direction == "D") {
} 1]]$y = knots[[1]]$y - 1
knots[[
}for (i in 1:9) {
<- move_knot(knots[[i]], knots[[i+1]])
new_coord if (new_coord$x != knots[[i+1]]$x | new_coord$y != knots[[i+1]]$y) {
+1]] <- new_coord
knots[[ielse{
} break
}
}<- c(visited_coord, paste(knots[[10]]$x, knots[[10]]$y,sep = ";"))
visited_coord
}
}
Result
length(unique(visited_coord))
[1] 2455